/* ==================================================================   
 * Created 2013-11-2上午12:21:22 by 郑伟
 * ==================================================================  
 *  EMV  Level2
 * Copyright (c) SZZCS S&T Co.ltd ShenZhen, 2012-2013 
 * ================================================================== 
 * 深圳市中磁计算机技术有限公司拥有该文件的使用、复制、修改和分发的许可权
 * 如果你想得到更多信息，请访问 <http://www.szzcs.com/cn>
 *
 * SZZCS S&T Co.ltd ShenZhen owns permission to use, copy, modify and 
 * distribute this documentation.
 * For more information on EMV, please 
 * see <http://www.szzcs.com/cn>.  
 * ================================================================== 
 */
package com.hangup.activity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

import com.devil.bbsclient.R;
import com.hangup.net.ActivityKeys;
import com.hangup.net.HttpUtil;
import com.hangup.pojo.Post;
import com.hangup.pojo.Reply;
import com.hangup.pojo.Student;
import com.hangup.util.GetCurrentDate;
import com.hangup.util.JsonUtil;
import com.hangup.util.NetWorkUtil;

import android.app.Activity;
import android.app.Dialog;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TableRow.LayoutParams;

public class TopicInfoActivity extends Activity {

	private String url;
	private String result;
	private Dialog dialog;
	PublicApplication pa;

	ArrayList<Reply> reply_;
	ArrayList<Student> stu_;

	private TextView titleTV;
	private TextView themeTV;
	private TextView textTV;
	private TextView timeTV;
	private TextView countTV;
	private ListView replyLV;

	private Button backBT;
	private Button btReply;
	String nickName;
	int postId;
	int postCount;

	private String replyText;
	PopupWindow _PopupWindow;
	Button btnclosePop, btnclose;;
	EditText et;

	private String reply_url;
	private String reply_result;
	private Dialog reply_dialog;

	Handler handler_ = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case 0:
				Toast.makeText(TopicInfoActivity.this, R.string.net,
						Toast.LENGTH_SHORT).show();
				break;
			case 1:
				dialog = NetWorkUtil.showDialog(TopicInfoActivity.this, null,
						"BBS论坛", "回复加载中,请稍等");
				dialog.show();
				break;
			case 2:
				dialog.cancel();
				Toast.makeText(TopicInfoActivity.this, "连接服务器异常!",
						Toast.LENGTH_LONG).show();
				break;
			case 3:
				dialog.cancel();
				Toast.makeText(TopicInfoActivity.this, "帖子回复加载失败...",
						Toast.LENGTH_SHORT).show();
				break;
			case 4:
				SimpleAdapter adapter = new SimpleAdapter(
						TopicInfoActivity.this, getData(reply_),
						R.layout.reply_list_item, new String[] { "nick",
								"time", "text" }, new int[] { R.id.reply_nick,
								R.id.reply_time, R.id.reply_text });
				replyLV.setAdapter(adapter);
				dialog.cancel();
				break;
			case 5:
				reply_dialog = NetWorkUtil.showDialog(TopicInfoActivity.this,
						null, "回复", "发表回复中,请稍等");
				reply_dialog.show();
				break;
			case 6:
				dialog.cancel();
				Toast.makeText(TopicInfoActivity.this, "发表回复失败...",
						Toast.LENGTH_SHORT).show();
				break;
			case 7:
				int auto = postCount + 1;
				countTV.setText("回复数:" + auto);
				getPostRelpy();
				break;
			default:
				break;
			}
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_topic_info);
		SysApplication.getInstance().addActivity(this);

		titleTV = (TextView) findViewById(R.id.topic_title_nick);
		themeTV = (TextView) findViewById(R.id.topic_info_theme);
		textTV = (TextView) findViewById(R.id.topic_info_text);
		timeTV = (TextView) findViewById(R.id.topic_info_time);
		countTV = (TextView) findViewById(R.id.topic_info_count);
		replyLV = (ListView) findViewById(R.id.topic_reply_list);
		backBT = (Button) findViewById(R.id.bt_topic_back);
		Bundle bundle = new Bundle();
		bundle = this.getIntent().getExtras();
		nickName = bundle.getString("nick");
		postId = bundle.getInt("post_id");
		pa = (PublicApplication) getApplication();
		btReply = (Button) findViewById(R.id.btReply);
		if (!pa.isLogin_flag()) {
			btReply.setVisibility(View.GONE);
		} else {
			btReply.setOnClickListener(new reply());
		}
		stu_ = pa.getStus_();
		Post post = pa.getPost_().get(pa.getPost_index());
		titleTV.setText(nickName + "的主题");
		themeTV.setText(post.getTheme());
		textTV.setText(post.getText());
		timeTV.setText("发表时间:" + post.getTime());
		postCount = post.getCount();
		countTV.setText("回复数:" + postCount);
		backBT.setOnClickListener(new back());
		if (NetWorkUtil.NetType(TopicInfoActivity.this) == null) {
			handler_.sendMessage(handler_.obtainMessage(0));
			return;
		}
		if (post.getCount() > 0) {
			getPostRelpy();
		}
	}

	public void getPostRelpy() {
		url = ActivityKeys.BASE_URL + ActivityKeys.REPLY_LIST_URL + "post_id="
				+ postId;
		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				handler_.sendMessage(handler_.obtainMessage(1));
				if (!NetWorkUtil.webServer()) {
					handler_.sendMessage(handler_.obtainMessage(2));
					return;
				}
				result = HttpUtil.getHttpPostResultForUrl(url);
				if (result == null) {
					handler_.sendMessage(handler_.obtainMessage(3));
				} else {
					reply_ = JsonUtil.parseList(result, Reply[].class);
					handler_.sendMessage(handler_.obtainMessage(4));// 更新回复UI
				}
			}
		}).start();
	}

	private final class back implements OnClickListener {

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			finish();
		}

	}

	private final class reply implements OnClickListener {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			LayoutInflater _LayoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
			ViewGroup _ViewGroup = (ViewGroup) _LayoutInflater.inflate(
					R.layout.sent, null, true);
			btnclosePop = (Button) _ViewGroup.findViewById(R.id.Button01);
			btnclose = (Button) _ViewGroup.findViewById(R.id.Button02);
			et = (EditText) _ViewGroup.findViewById(R.id.EditText01);
			btnclose.setOnClickListener(new closePopup());
			// 当点击发送后的响应
			btnclosePop.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if (!et.getText().toString().trim().equals("")) {
						if (_PopupWindow != null && _PopupWindow.isShowing()) {
							replyText = et.getText().toString().trim();
							addReply();
							_PopupWindow.dismiss(); // 关闭发送框
						}
					} else {
						Toast.makeText(TopicInfoActivity.this, "回复内容不能为空，谢谢",
								Toast.LENGTH_LONG).show();
					}

				}
			});

			_PopupWindow = new PopupWindow(_ViewGroup,
					LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, true);
			_PopupWindow.setBackgroundDrawable(new BitmapDrawable());
			_PopupWindow.setAnimationStyle(R.style.PopupAnimation);
			_PopupWindow.showAtLocation(findViewById(R.id.topic_dialog),
					Gravity.CENTER | Gravity.CENTER, 0, 0);
			_PopupWindow.update();
		}

	}

	class closePopup implements OnClickListener {
		@Override
		public void onClick(View v) {
			if (_PopupWindow != null && _PopupWindow.isShowing()) {
				_PopupWindow.dismiss();
			}
		}
	}

	private ArrayList<HashMap<String, Object>> getData(ArrayList<Reply> replys) {
		Collections.reverse(replys);
		ArrayList<HashMap<String, Object>> dlist = new ArrayList<HashMap<String, Object>>();
		if (replys.size() > 0) {
			for (Reply reply : replys) {
				HashMap<String, Object> map = new HashMap<String, Object>();
				for (Student stu : stu_) {
					if (reply.getStu_id() == stu.getStu_id()) {
						map.put("nick", stu.getStu_nick() + "的回复:");
						break;
					}
				}
				map.put("time", reply.getTime());
				map.put("text", reply.getText());
				dlist.add(map);
			}
		}
		return dlist;
	}

	private void addReply() {
		reply_url = ActivityKeys.BASE_URL + ActivityKeys.ADD_REPLY_URL;
		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				handler_.sendMessage(handler_.obtainMessage(5));
				if (!NetWorkUtil.webServer()) {
					handler_.sendMessage(handler_.obtainMessage(2));
					return;
				}
				Reply reply = new Reply();
				reply.setText(replyText);
				reply.setPost_id(postId);
				reply.setTime(GetCurrentDate.getCurrentTime());
				reply.setStu_id(pa.getStu().getStu_id());
				reply_result = HttpUtil.postHttpResponseText(reply_url,
						JsonUtil.format(reply));
				if (reply_result == null) {// 发表回复失败
					handler_.sendMessage(handler_.obtainMessage(6));
					return;
				}
				reply_dialog.cancel();
				handler_.sendMessage(handler_.obtainMessage(7));
			}
		}).start();
	}
}
